<template>
	<view class="content">
		
		<!-- 自定义导航 -->
		<u-navbar
			title="德亿安" 
			fixed
			:border="false"
			:safeAreaInsetTop="true"
			v-if="isNavBarVisible"
		>
			<view class="location" slot="left" @click="openCityPicker">
				<text>{{ selectedCity || '深圳市' }}</text>
				<u-icon name="arrow-down-fill" size="20rpx" color="#333333"></u-icon>
			</view> 
			<!-- #ifdef MP -->
			<view class="search mp" slot="center">
				<view class="search-input"><text>搜索目的地/充电桩</text></view>
				<view class="icon"><text>搜索</text></view>
			</view>
			<!-- #endif -->
			
			<!-- #ifndef MP -->
			<view class="search" style="margin: 0 30rpx 0 200rpx;height: 70rpx;" slot="center">
				<view class="search-input" style="height: 70rpx;"><text>搜索目的地/充电桩</text></view>
				<view class="icon" style="height: 70rpx;width: 126rpx;"><text>搜索</text></view>
			</view>
			<!-- #endif -->
		</u-navbar>
		
		<!-- 轮播图 -->
		<view class="u-demo-block" ref="swiper">
			<u-swiper 
				:list="banner" 
				circular 
				:indicator="true" 
				:autoplay="true" 
				height="392rpx" 
				indicatorActiveColor="#DDE4F0"
				indicatorInactiveColor="#fff"
				indicatorMode="dot"
			></u-swiper>
		</view>
		
		<!-- 搜索导航栏 -->
		<view class="header" ref="header">
			<view class="location" @click="openCityPicker">
				<text>{{ selectedCity || '深圳市' }}</text>
				<u-icon name="arrow-down-fill" size="20rpx" color="#333333"></u-icon>
			</view>
			<view class="search" @click="gotolist">
				<view class="search-input"><text>搜索目的地/充电桩</text></view>
				<view class="icon"><text>搜索</text></view>
			</view>
		</view>
		
		<!-- 内容区域 -->
		<view class="main" 
			:class="{'is-fixed': isFixed}"
			:style="{top: (navBarHeight - 1) + 'px'}"
		>
			<view class="nav-tabs">
				<view class="tab " :class="{active: current == 1}" @click="changeTab(1)">推荐电站</view>
				<view class="tab" :class="{active: current == 2}" @click="changeTab(2)">{{ $t('常用电站') }}</view> 
				<view class="tab" :class="{active: current == 3}" @click="changeTab(3)">收藏电站</view>
			</view>
			
			<view class="filter" v-if="current == 1">
				<view class="filter-item" @click="openFilter('parking')">
					<text>停车费</text>
					<u-icon name="arrow-down-fill" size="20rpx" color="#333333"></u-icon>
				</view>
				<view class="filter-item" @click="openFilter('charging')">
					<text>充电方式</text>
					<u-icon name="arrow-down-fill" size="20rpx" color="#333333"></u-icon>
				</view>
				<view class="filter-item" @click="openFilter('facility')">
					<text>配套服务</text>
					<u-icon name="arrow-down-fill" size="20rpx" color="#333333"></u-icon>
				</view>
				<view class="filter-item" @click="openFilter('more')">
					<text>更多筛选</text>
					<u-icon name="arrow-down-fill" size="20rpx" color="#333333"></u-icon>
				</view>
			</view>
			
			<view v-else style="border-bottom: 1rpx solid #eee;"></view>
		</view>
		
		<!-- 列表 -->
		<view class="list" v-if="list && list.length > 0">
			<charger-item :list="list" :distance="current == 1" @gotodetail="gotodetail"></charger-item>
		</view>
			
		<!-- 空状态 -->
		<view class="empty" v-else><u-empty mode="data"></u-empty></view>
		
		<!-- 加载更多 -->
		<u-loadmore v-if="list && list.length > 0" :status="loadMoreStatus" />
		
		<com-map ref="commap" @myevent="setlocation"></com-map>
		<com-tabbar :currentTab="currentTab"></com-tabbar>
		
		<!-- 更多筛选弹窗 -->
		<filter-popup
			:show="showFilter"
			:filter-type="filterType"
			:active-filters="formData"
			@close="closeFilter"
			@confirm="handleFilterConfirm"
		/>
		
		<!-- 城市选择器 -->
		<city-select 
			:show="showCityPicker" 
			@update:show="showCityPicker = $event"
			@confirm="handleCitySelected"
		></city-select>
		
		<!-- 回到顶部 -->
		<u-back-top :scroll-top="scrollTop"></u-back-top>
	</view>
</template>

<script>
	import { mapState, mapActions } from 'vuex'
	import { getOrderAndNumber, isEmpty } from '@/utils/index.js';
	import { getNavBarHeight, setNavBarHeightVar } from '@/utils/system.js'
	import CityPicker from '@/components/city-picker/index.vue'
	import CitySelect from '@/components/city-select/city-select.vue'
	import { getIsFleetUser } from '@/common/cacheManager.js'
	export default {
		components: {
			CityPicker,
			CitySelect
		},
		data() {
			return {
				banner: [],
				currentTab: "home",
				current: 1,
				keyword: '',
				list: [],
				latitude: '',
				longitude: '',
				showFilter: false,
				filterType: 'more', // 可选值：parking(停车费)、charging(充电方式)、facility(配套服务)、more(更多筛选)
				scrollTop: 0,
				headerTop: 0, // header 节点距离顶部的距离
				isFixed: false,
				navBarInfo: null,
				statusBarHeight: 0,
				navBarHeight: 0,
				isNavBarVisible: false,
				
				isLoading: false,
				isFinished: false,
				formData: {
					pageNo: 1,
					pageSize: 10,
					userLatitude: 13.9431,
					userLongitude: 158.4491,
					
					parkingFee: [], // 停车费筛选
					chargingTypes: [], // 充电方式筛选
					serviceTypes: [], // 配套服务筛选
					technologyFeatures: [] ,// 其他技术特性筛选
					city: '',
				},
				showCityPicker: false,
				selectedCity: '深圳市',
				isShowArea:false,   //是否显示地区
				isAddNational:false //是否添加全国
			}
		},
		onPageScroll(e) {
			this.handleScroll(e)
		},
		onReachBottom() {
			// 根据当前选中的tab调用对应的列表加载方法
			if (this.current === 1) {
				this.getlist()
			} else if (this.current === 2) {
				this.getUsedList()
			} else if (this.current === 3) {
				this.getUserCollectList()
			}
		},
		async onLoad(options) {
			if (!isEmpty(options.q)) {
				this.decodeUrl(options.q);
			}
			
			// 获取导航栏信息
			this.navBarInfo = getNavBarHeight()
			// 设置headerTop初始值
			this.headerTop = this.navBarInfo.navBarHeight
			
			// 设置CSS变量
			const { statusBarHeight, navBarHeight } = setNavBarHeightVar()
			// 更新组件内的状态
			this.statusBarHeight = statusBarHeight
			this.navBarHeight = navBarHeight
			
			// 如果有定位信息，更新本地状态
			if (this.mylocationState && this.mylocation) {
				this.selectedCity = this.mylocation.city || '深圳市'
				this.latitude = this.mylocation.latitude
				this.longitude = this.mylocation.longitude
				
				// 确保formData中的位置与全局状态一致
				this.formData.userLatitude = this.mylocation.latitude
				this.formData.userLongitude = this.mylocation.longitude
			}
			
			// 获取轮播图
			this.bannerList();
			
			// 获取列表数据
			this.getlist();
			
			// 监听登录成功的事件
			// uni.$on('loginSuccessEvent', () => this.changeTab(1));
			
			// 修改监听事件，登录成功后执行用户请求
			uni.$on('loginSuccessEvent', async () => {
				console.log("登录成功");
				// 添加 getFleet() 方法调用
				const isFleetUser = await getIsFleetUser({
				  expireTime: 30 * 60 * 1000, // 缓存30分钟
				  showLoading: true,
				  loadingText: '获取用户状态中...'
				})
				
				console.log('是否是车队用户:', isFleetUser)
				this.changeTab(1);
			});
			
			
			
		},
		mounted() {
			this.$nextTick(() => this.initHeaderPosition())
		},
		computed: {
			//引入store全局变量
			...mapState(['mylocation', 'mylocationState']),
			loadMoreStatus() {
				if (this.isLoading) return 'loading'
				if (this.isFinished) return 'nomore'
				return 'loadmore'
			}
		},
		methods: {
			decodeUrl(url) {
				const result = getOrderAndNumber(decodeURIComponent(url));
				if (!result) {
					return uni.$u.toast('识别失败');
				}
				// 通过桩的编号获取电站id
				this.$http_api.getPileId({ terminalId: result.terminalId, gunCode: result.gunCode }).then(data => {
					uni.navigateTo({
						url: `/pages/scan/step2?id=${data.stationId}&terminalId=${data.id}`
					})
				});
			},
			
			bannerList() {
				this.$http_api.getBannerList({ position: 1 }).then(res => {
					this.banner = res.map(item => item.picUrl)
				});
			},
			
			changeTab(index) {
				this.current = index;
				this.formData.pageNo = 1;
				this.list = [];
				this.isLoading = false;
				this.isFinished = false;
				if (index == 1) {
					this.getlist();
					return;
				}
				if (index == 2) {
					this.getUsedList();
					return;
				}
				this.getUserCollectList();
			},
			
			// 常用电站
			getUsedList() {
				if (this.isFinished || this.isLoading) return
				this.isLoading = true
				this.$http_api.chargingUsedList({ pageNo: this.formData.pageNo, pageSize: 10 }).then(res => {
					if (!res) {
						this.isFinished = true
						return
					}
					let { records = [], total = 0, current = 1, pages = 1 } = res || {}
					
					// 处理标签
					records = this.processStationLabels(records)
					
					this.list = this.formData.pageNo === 1 ? records : [...this.list, ...records]
					this.isFinished = current >= pages
					this.formData.pageNo++
				}).catch(err => {
					this.isFinished = true
				}).finally(() => {
					this.isLoading = false
				})
			},
			
			// 获取我收藏的电站
			getUserCollectList() {
				if (this.isFinished || this.isLoading) return
				this.isLoading = true
				this.$http_api.stationFavoriteList({ page: this.formData.pageNo, size: 10 }).then(res => {
					if (!res) {
						this.isFinished = true
						return
					}
					
					let { records = [], total = 0, current = 1, pages = 1 } = res || {}
					
					// 处理标签
					records = this.processStationLabels(records)
					
					this.list = this.formData.pageNo === 1 ? records : [...this.list, ...records]
					this.isFinished = current >= pages
					this.formData.pageNo++
				}).catch(err => {
					console.error('Error fetching favorite stations:', err)
					this.isFinished = true
				}).finally(() => {
					this.isLoading = false
				})
			},
			
			openFilter(type) {
				this.filterType = type
				this.showFilter = true
			},
			
			// 获取列表数据，处理定位、刷新和筛选条件
			getlist(isRefresh = false) {
				// 刷新时重置页码
				if (isRefresh) {
					this.formData.pageNo = 1
					this.list = []
					this.isFinished = false
				}
				
				// 已加载完或正在加载中，直接返回
				if (this.isFinished || this.isLoading) return
				
				// 判断定位状态
				if (!this.mylocationState) {
					this.$nextTick(() => this.$refs.commap.setlocation())
					return
				}
				
				this.isLoading = true
				
				// 确保使用当前的位置信息
				this.formData.userLatitude = this.mylocation.latitude
				this.formData.userLongitude = this.mylocation.longitude
				this.formData.city = this.selectedCity;
				
				// 请求充电站列表 
				setTimeout(() => this.fetchChargingStations(), 300)
			},
			
			// 提取出请求充电站列表的方法
			fetchChargingStations() {
				this.$http_api.chargingList(this.formData).then((res) => {
					if (!res) {
						this.isFinished = true
						return
					}
					let { records = [], total = 0, current = 1, pages = 1 } = res || {}
					records = this.processStationLabels(records); // 处理标签
					this.list = this.formData.pageNo === 1 ? records : [...this.list, ...records]; // 追加数据
					this.isFinished = current >= pages; // 判断是否加载完成
					this.formData.pageNo++; // 更新页码
				}).finally(() => {
					this.isLoading = false
				})
			},
			
			// 处理充电站标签
			processStationLabels(records) {
				if (!Array.isArray(records)) {
					return []
				}
				
				return records.map(item => {
					try {
						let labels = [];
						// 配套服务
						if (item.serviceTypes && Array.isArray(item.serviceTypes)) {
							labels.push(...this.getFilterLabels('serviceType', item.serviceTypes))
						}
						// 科技特色
						if (item.technologyFeatures && Array.isArray(item.technologyFeatures)) {
							labels.push(...this.getFilterLabels('technologyFeatures', item.technologyFeatures))
						}
						// 停车场、停车费、充电方式标签为单个
						labels = this.getFilterOtherLabels(item.parkingArea, item.parkingFee, item.chargingType, labels)
						item.labels = labels
						return item;
					} catch (error) {
						item.labels = []
						return item
					}
				})  
			},
			
			//跳转详情
			gotodetail(id) {
				uni.navigateTo({
					url:"/pages/index/detail?id="+id
				})
			},
			//重新定位
			cxdw(){
				this.getlist()
			},
			//跳转搜索列表
			gotolist(){
				uni.navigateTo({
					url:'/pages/list/list'
				})
			},
			//子组件传值 - 从地图组件获取位置
			setlocation(e) {
				
				// 统一更新全局位置状态
				this.updateLocationState({ 
					latitude: e.latitude, 
					longitude: e.longitude, 
					city: e.city || this.selectedCity ,
				})
				
				// 重新加载列表
				this.getlist(true)
			},
			closeFilter() {
				this.showFilter = false
			},
			
			handleFilterConfirm(activeFilters) {
				if (!activeFilters) {
					return
				}
				// 更新 formData，移除所有基础字段外的筛选条件
				const baseKeys = ['pageNo', 'pageSize', 'userLatitude', 'userLongitude']
				Object.keys(this.formData).forEach(key => {
					if (!baseKeys.includes(key)) {
						delete this.formData[key]
					}
				})
				// 添加新的筛选条件
				Object.keys(activeFilters).forEach(key => {
					const value = activeFilters[key] || []
					if (Array.isArray(value) && value.length > 0) {
						this.formData[key] = value
					}
				})
				this.formData.serviceTypes = this.formData.serviceType || [];
				delete this.formData.serviceType;
				this.getlist(true)
			},
			
			// 初始化header位置
			initHeaderPosition() {
				const query = uni.createSelectorQuery().in(this)
				// 获取header到顶部的距离
				query.select('.header').boundingClientRect(data => {
					if (data) {
						this.headerTop = data.top
					}
				}).exec()
			},
			
			// 修改滚动处理函数
			handleScroll(e) {
				this.scrollTop = e.scrollTop
				
				this.isNavBarVisible = this.scrollTop > this.headerTop
				this.isFixed = this.scrollTop > this.headerTop
			},
			
			getFilterLabels(type, indices) {
				if (!Array.isArray(indices) || !this.$store.state[type]) {
					return [];
				}
				const labels = indices.map(index => {
					const item = this.$store.state[type].find(label => label.value == index)
					return item.name.replaceAll('\r\n', '')
				})
				return labels
			},
			// 单选筛选条件
			getFilterOtherLabels(parkingArea, parkingFee, chargingType, labels) {
				// 停车场
				const parkingAreaLabel = this.$store.state.parkingType.find((item, index) => parkingArea == item.value)
				if (parkingAreaLabel) {
					labels.push(parkingAreaLabel.name)
				}
				// 停车费
				const parkingFeeLabel = this.$store.state.parkingFee.find((item, index) => parkingFee == item.value)
				if (parkingFeeLabel) {
					labels.push(parkingFeeLabel.name)
				}
				// 充电方式
				const chargingTypeLabel = this.$store.state.chargingType.find((item, index) => chargingType == item.value)
				if (chargingTypeLabel) {
					labels.push(chargingTypeLabel.name)
				}
				return labels;
			},
			openCityPicker() {
				this.showCityPicker = true
			},
			// 城市选择确认
			handleCitySelected(result) {
				if (!result || !result.city) {
					return
				}
				const { lat, lng } = result.city.location || {}
				const cityName = result.city.name || result.city.label || '深圳市'
				// 统一更新全局位置状态
				this.updateLocationState({ 
					latitude: this.latitude || 13.9431, 
					longitude: this.longitude || 158.4491, 
					city: cityName 
				})
				// 重新加载列表
				this.getlist(true)
			},
			// 统一更新位置状态的方法
			updateLocationState(locationData) {
				const { latitude, longitude, city } = locationData
				
				// 更新本地状态 - 确保使用数值类型
				this.latitude = parseFloat(latitude)
				this.longitude = parseFloat(longitude)
				this.selectedCity = city
				
				// 更新表单数据 - 确保使用数值类型
				this.formData.userLatitude = parseFloat(latitude)
				this.formData.userLongitude = parseFloat(longitude)
				
				// 更新Vuex状态 - 确保传递数值类型
				this.$store.dispatch('getlocationAction', {
					latitude: parseFloat(latitude),
					longitude: parseFloat(longitude),
					city
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	
	.content {
		width: 100%;
		box-sizing: border-box;
		// padding-top: var(--nav-bar-height);
	}
	
	.u-demo-block{
		width: 100%;
	}
	
	.sticky {
		position: sticky;
		top: calc(var(--window-top) - 2rpx); 
	}
	
	.header {
		padding: 20rpx 30rpx;
		display: flex;
		align-items: center;
		background: #fff;
		margin: 20rpx;
		border-radius: 28rpx;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		will-change: transform, opacity;
	}
	
	.location {
		display: flex;
		align-items: center;
		margin-right: 20rpx;
		
		text {
			font-size: 32rpx;
			margin-right: 4rpx;
			font-weight: 500;
			font-family: "PINGFANG";
		}
	}
	
	.search {
		flex: 1;
		display: flex;
		align-items: center;
		
		.search-input {
			background: #F3F3F3;
			border-radius: 28rpx;
			height: 83rpx;
			position: relative;
			flex: 2;
			display: flex;
			align-items: center;
			padding-left: 20rpx;
			
			text {
				font-weight: 400;
				font-family: "PINGFANG";
				font-size: 24rpx;
				color: #A09FA4;
			}
		}
		
		.icon {
			width: 139rpx;
			height: 77rpx;
			position: absolute;
			right: 30rpx;
			background: url(~@/static/home/searchBg.png) no-repeat;
			background-size: 100% 100%;
			
			display: flex;
			align-items: center;
			justify-content: center;
			
			text {
				font-weight: 400;
				font-family: "PINGFANG";
				font-size: 28rpx;
				color: #fff;
			}
		}
	}
	
	.mp {
		margin: 0 200rpx 0 160rpx;
		transition: all 0.2s;
		.search-input {
			height: 65rpx;
		}
		.icon {
			width: 127rpx;
			height: 65rpx;
			right: 200rpx;
		}
	}
	
	.main {
		background: #fff;
		margin: 0 20rpx;
		border-radius: 20rpx 20rpx 0 0;
		overflow: hidden;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		will-change: transform;
		
		&.is-fixed {
			position: sticky;
			z-index: 10;
			margin: 0;
			padding: 0 20rpx;
			border-radius: 0;
		}
		
		.nav-tabs {
			display: flex;
			justify-content: space-between;
			padding: 20rpx 30rpx;
			background: #fff;
			
			.tab {
				font-size: 28rpx;
				color: #777;
				background: #F6F6F6;
				width: 206rpx;
				height: 76rpx;
				border-radius: 69rpx;
				font-family: "PINGFANG";
				
				display: flex;
				align-items: center;
				justify-content: center;
				padding-bottom: 6rpx;
				
				&.active {
					color: #fff;
					background: url(~@/static/home/navitem.png) no-repeat;
					background-size: 100% 100%;
				}
			}
		}
		
		.filter {
			display: flex;
			justify-content: space-between;
			padding: 20rpx 30rpx;
			border-bottom: 1px solid #eee;
			background: #fff;
			
			.filter-item {
				display: flex;
				align-items: center;
				
				text {
					color: #777;
					margin-right: 4rpx;
					font-size: 24rpx;
					font-weight: 400;
					font-family: "PINGFANG";
				}
			}
		}
	}
	
	.list {
		margin: 0 20rpx 30rpx 20rpx;
	}
	
	.filter-popup {
		width: 100vw;
		max-height: 80vh;
		background: #fff;
		display: flex;
		flex-direction: column;
		border-radius: 30rpx 30rpx 0 0;
		
		.filter-header {
			padding: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			flex-shrink: 0;
			
			text {
				font-family: "PINGFANG";
				font-size: 32rpx;
				font-weight: 400;
				color: #333;
				flex: 2;
				text-align: center;
			}
		}
		
		.filter-content {
			flex: 1;
			overflow-y: auto;
			padding: 20rpx 30rpx;
			width: calc(100% - 60rpx);
			-webkit-overflow-scrolling: touch;
			
			.filter-section {
				margin-bottom: 40rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.section-title {
					font-size: 28rpx;
					font-weight: 600;
					color: #333;
					font-family: "PINGFANG";
					margin-bottom: 20rpx;
				}
				
				.section-tags {
					display: flex;
					flex-wrap: wrap;
					margin: 20rpx -10rpx 0;
					
					.tag {
						width: calc((100% - 60rpx) / 3); 
						margin: 0 10rpx 20rpx;
						padding: 15rpx 20rpx;
						background: #F6F6F6;
						border-radius: 21rpx;
						border: 1rpx solid #F6F6F6;
						display: flex;
						align-items: center;
						justify-content: center;
						box-sizing: border-box;
						
						text {
							font-size: 24rpx;
							color: #333;
							font-family: "PINGFANG";
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
							max-width: 100%;
						}
						
						&.active {
							background: #E5EFFF;
							border: 1rpx solid #1C6EFB;
							
							text {
								color: #1C6EFB;
							}
						}
					}
				}
			}
		}
		
		.filter-footer {
			padding: 20rpx 30rpx;
			display: flex;
			gap: 20rpx;
			border-top: 1rpx solid #eee;
			flex-shrink: 0;
			
			.btn {
				flex: 1;
				height: 85rpx;
				border-radius: 43rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				font-weight: 400;
				font-family: "PINGFANG";
				
				&.reset {
					background: #fff;
					color: #1C6EFB;
					border: 1rpx solid #1C6EFB;
				}
				
				&.confirm {
					background: #1C6EFB;
					color: #fff;
				}
			}
		}
	}
</style>